
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>课程管理系统</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .table-container {
            margin-top: 20px;
        }
        .pagination-info {
            margin-top: 10px;
        }
        .search-form {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<div class="container">
    <h2 class="my-4 text-center">课程管理系统</h2>

    <!-- 搜索表单 -->
    <div class="search-form">
        <form id="searchForm" class="row g-3">
            <div class="col-md-4">
                <label for="courseName" class="form-label">课程名称</label>
                <input type="text" class="form-control" id="courseName" placeholder="输入课程名称">
            </div>
            <div class="col-md-4">
                <label for="teacherNo" class="form-label">授课教师</label>
                <select class="form-select" id="teacherNo">
                    <option value="">全部教师</option>
                    <!-- 教师选项将通过AJAX动态加载 -->
                </select>
            </div>
            <div class="col-md-4 d-flex align-items-end">
                <button type="button" class="btn btn-primary me-2" id="searchBtn">
                    <i class="fas fa-search me-1"></i>搜索
                </button>
                <button type="button" class="btn btn-success" id="addCourseBtn" data-bs-toggle="modal" data-bs-target="#courseModal">
                    <i class="fas fa-plus me-1"></i>新增课程
                </button>
            </div>
        </form>
    </div>

    <!-- 课程表格 -->
    <div class="table-container">
        <table class="table table-striped table-hover">
            <thead class="table-dark">
            <tr>
                <th>课程编号</th>
                <th>课程名称</th>
                <th>学分</th>
                <th>授课教师</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="courseTableBody">
            <!-- 表格内容将通过AJAX动态加载 -->
            </tbody>
        </table>

        <!-- 分页信息 -->
        <div class="row">
            <div class="col-md-6 pagination-info" id="paginationInfo">
                显示第 0 至 0 项，共 0 项
            </div>
            <div class="col-md-6">
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-end" id="pagination">
                        <!-- 分页按钮将通过AJAX动态加载 -->
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</div>

<!-- 新增/编辑课程模态框 -->
<div class="modal fade" id="courseModal" tabindex="-1" aria-labelledby="courseModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="courseModalLabel">新增课程</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="courseForm">
                    <input type="hidden" id="editCourseNo">
                    <div class="mb-3">
                        <label for="modalCourseName" class="form-label">课程名称</label>
                        <input type="text" class="form-control" id="modalCourseName" required>
                    </div>
                    <div class="mb-3">
                        <label for="modalCredit" class="form-label">学分</label>
                        <input type="text" class="form-control" id="modalCredit" required>
                    </div>
                    <div class="mb-3">
                        <label for="modalTeacherNo" class="form-label">授课教师</label>
                        <select class="form-select" id="modalTeacherNo" required>
                            <option value="">请选择教师</option>
                            <!-- 教师选项将通过AJAX动态加载 -->
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveCourseBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                确定要删除这条课程记录吗？此操作不可逆！
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确定删除</button>
            </div>
        </div>
    </div>
</div>

<!-- jQuery, Bootstrap JS -->
<!--<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>-->

<script src="js/jquery-3.6.0.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>

<script>
    $(document).ready(function() {
        let currentPage = 1;
        let pageSize = 10;
        let totalItems = 0;
        let deleteCourseNo = null;

        // 初始化页面
        loadTeachers();
        loadCourses();

        function loadTeachers() {
            $.ajax({
                url: '/course/getAllTeachers',
                type: 'GET',
                success: function(response) {
                    // 根据实际返回结构调整
                    const teachers = response.data || response.result || [];

                    // 清空下拉框
                    $('#teacherNo').empty().append('<option value="">全部教师</option>');
                    $('#modalTeacherNo').empty().append('<option value="">请选择教师</option>');

                    // 遍历教师数据 - 使用正确的字段名 'name'
                    teachers.forEach(teacher => {
                        // 创建选项文本 - 使用 name 字段
                        const optionText = teacher.name || `教师 ${teacher.teacherNo}`;

                        // 添加到下拉框
                        $('#teacherNo').append(`<option value="${teacher.teacherNo}">${optionText}</option>`);
                        $('#modalTeacherNo').append(`<option value="${teacher.teacherNo}">${optionText}</option>`);
                    });
                },
                error: function(xhr) {
                    console.error('加载教师列表失败:', xhr.responseJSON?.msg || '服务器错误');
                    alert('加载教师列表失败，请稍后重试');
                }
            });
        }

        // 加载课程数据
        function loadCourses() {
            const courseName = $('#courseName').val();
            const teacherNo = $('#teacherNo').val();

            $.ajax({
                url: '/course/pageCourse',
                type: 'GET',
                data: {
                    courseName: courseName,
                    teacherNo: teacherNo,
                    pageSize: pageSize,
                    current: currentPage
                },
                success: function(page) {
                    totalItems = page.total;
                    renderCourses(page.records);
                    renderPagination();
                    updatePaginationInfo(page.records.length);
                },
                error: function(xhr) {
                    alert('加载课程数据失败: ' + xhr.responseJSON?.msg || '服务器错误');
                }
            });
        }

        // 渲染课程表格
        function renderCourses(courses) {
            const $tbody = $('#courseTableBody');
            $tbody.empty();

            if (courses.length === 0) {
                $tbody.append('<tr><td colspan="5" class="text-center">暂无数据</td></tr>');
                return;
            }

            // 先获取所有教师数据用于查找
            const teacherOptions = {};
            $('#teacherNo option').each(function() {
                if (this.value) {
                    teacherOptions[this.value] = $(this).text();
                }
            });

            courses.forEach(course => {
                const teacherName = teacherOptions[course.teacherNo] || `教师 ${course.teacherNo}`;

                $tbody.append(`
            <tr>
                <td>${course.courseNo}</td>
                <td>${course.courseName}</td>
                <td>${course.credit}</td>
                <td>${teacherName}</td>
                <td>
                    <button class="btn btn-sm btn-warning edit-btn" data-id="${course.courseNo}">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button class="btn btn-sm btn-danger delete-btn" data-id="${course.courseNo}">
                        <i class="fas fa-trash-alt"></i> 删除
                    </button>
                </td>
            </tr>
                    `);
            });

            // 绑定编辑按钮事件
            $('.edit-btn').click(function() {
                const courseNo = $(this).data('id');
                editCourse(courseNo);
            });

            // 绑定删除按钮事件
            $('.delete-btn').click(function() {
                deleteCourseNo = $(this).data('id');
                $('#deleteModal').modal('show');
            });
        }

        // 渲染分页
        function renderPagination() {
            const totalPages = Math.ceil(totalItems / pageSize);
            const $pagination = $('#pagination');
            $pagination.empty();

            if (totalPages <= 1) return;

            // 上一页按钮
            $pagination.append(`
                    <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                        <a class="page-link" href="#" aria-label="Previous" data-page="${currentPage - 1}">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                `);

            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                $pagination.append(`
                        <li class="page-item ${i === currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" data-page="${i}">${i}</a>
                        </li>
                    `);
            }

            // 下一页按钮
            $pagination.append(`
                    <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                        <a class="page-link" href="#" aria-label="Next" data-page="${currentPage + 1}">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                `);

            // 绑定分页按钮事件
            $('.page-link').click(function(e) {
                e.preventDefault();
                const page = $(this).data('page');
                if (page >= 1 && page <= totalPages && page !== currentPage) {
                    currentPage = page;
                    loadCourses();
                }
            });
        }

        // 更新分页信息
        function updatePaginationInfo(count) {
            const start = (currentPage - 1) * pageSize + 1;
            const end = Math.min(start + count - 1, totalItems);
            $('#paginationInfo').text(`显示第 ${start} 至 ${end} 项，共 ${totalItems} 项`);
        }

        function editCourse(courseNo) {
            $.ajax({
                url: '/course/getCourse?courseNo=' + courseNo, // 根据实际API调整
                type: 'GET',
                success: function(response) {
                    const course = response.data || response; // 根据实际API响应结构调整
                    $('#editCourseNo').val(course.courseNo);
                    $('#modalCourseName').val(course.courseName);
                    $('#modalCredit').val(course.credit);
                    $('#modalTeacherNo').val(course.teacherNo);
                    $('#courseModalLabel').text('编辑课程');
                    $('#courseModal').modal('show');
                },
                error: function(xhr) {
                    alert('获取课程信息失败: ' + xhr.responseJSON?.msg || '服务器错误');
                }
            });
        }

        // 搜索按钮点击事件
        $('#searchBtn').click(function() {
            currentPage = 1;
            loadCourses();
        });

        // 新增课程按钮点击事件
        $('#addCourseBtn').click(function() {
            $('#editCourseNo').val('');
            $('#modalCourseName').val('');
            $('#modalCredit').val('');
            $('#modalTeacherNo').val('');
            $('#courseModalLabel').text('新增课程');
            $('#courseForm')[0].reset();
        });

        $('#saveCourseBtn').click(function() {
            const courseNo = $('#editCourseNo').val();
            const courseName = $('#modalCourseName').val();
            const credit = $('#modalCredit').val();
            const teacherNo = $('#modalTeacherNo').val();

            if (!courseName || !credit || !teacherNo) {
                alert('请填写所有必填字段！');
                return;
            }

            // 创建课程对象 - 根据后端API要求调整字段名
            const courseData = {
                courseName: courseName,
                credit: parseInt(credit),
                teacherNo: teacherNo
            };

            // 如果是编辑，添加课程编号到数据中
            if (courseNo) {
                courseData.courseNo = courseNo;
            }

            const isEdit = !!courseNo;
            const url = isEdit ? '/course/updateCourse' : '/course/addCourse';
            const method = isEdit ? 'PUT' : 'POST';

            $.ajax({
                url: url,
                type: method,
                contentType: 'application/json',
                data: JSON.stringify(courseData),
                success: function(response) {
                    if (response.msg === 'success' || response.code === 200) { // 根据实际API响应调整
                        $('#courseModal').modal('hide');
                        loadCourses();
                        alert(isEdit ? '课程更新成功！' : '课程添加成功！');
                    } else {
                        alert('操作失败: ' + (response.msg || '未知错误'));
                    }
                },
                error: function(xhr) {
                    alert('操作失败: ' + (xhr.responseJSON?.msg || '服务器错误'));
                }
            });
        });

        // 确认删除按钮点击事件
        $('#confirmDeleteBtn').click(function() {
            if (!deleteCourseNo) return;

            $.ajax({
                url: '/course/deleteCourse',
                type: 'DELETE',
                data: {
                    courseNo: deleteCourseNo
                },
                success: function(response) {
                    if (response.msg === 'success') {
                        $('#deleteModal').modal('hide');
                        loadCourses();
                        alert('课程删除成功！');
                    } else {
                        alert(response.msg);
                    }
                },
                error: function(xhr) {
                    alert('删除课程失败: ' + (xhr.responseJSON?.msg || '服务器错误'));
                }
            });
        });
    });
</script>
</body>
</html>